package org.brownflat.fxdate.dao;

import org.brownflat.fxdate.model.Role;
import org.brownflat.fxdate.model.User;
import org.brownflat.fxdate.security.FXDateAuthenticationException;
import org.brownflat.fxdate.util.HashGenerator;
import org.hibernate.Criteria;
import org.springframework.stereotype.Repository;

import java.util.Collection;

import static org.hibernate.criterion.Restrictions.eq;

/**
 * <p>&copy Rupert Jones 2011</p>
 *
 * @author rup
 */
@Repository
public class UserDAO extends AbstractHibernateDAO<User> {

    public UserDAO() {
        super(User.class);
    }

    public User authenticate(String username, String password) {
        String hash = HashGenerator.hash(password);
        Criteria criteria = getCriteria().add(eq("username", username)).add(eq("password", hash));
        User user = (User) criteria.uniqueResult();

        if (user == null) {
            throw new FXDateAuthenticationException("Authentication failed");
        }
        return user;
    }

    public User find(String userName) {
        Criteria criteria = getCriteria().add(eq("username", userName));
        return (User) criteria.uniqueResult();
    }

    @SuppressWarnings("unchecked")
    public Collection<User> findAllAdministrators() {
        return (Collection<User>) getCriteria().createAlias("roles", "roles").add(eq("roles.name", Role.ROLE_ADMIN)).list();
    }

    public User findUnknownUser() {
        return find("UNKNOWN");
    }
}
